package cn.tt.tuantuanerp.tuantuanerp.purchase.webapi.service.impl;

import cn.tt.tuantuanerp.tuantuanerp.comment.ex.ServiceException;
import cn.tt.tuantuanerp.tuantuanerp.comment.pojo.dto.PurchaseStandardDTO;
import cn.tt.tuantuanerp.tuantuanerp.comment.pojo.entity.Purchase;
import cn.tt.tuantuanerp.tuantuanerp.comment.pojo.entity.PurchaseProduct;
import cn.tt.tuantuanerp.tuantuanerp.comment.pojo.entity.SkuPurchaseInfo;
import cn.tt.tuantuanerp.tuantuanerp.comment.pojo.vo.*;
import cn.tt.tuantuanerp.tuantuanerp.comment.security.LoginPrincipal;
import cn.tt.tuantuanerp.tuantuanerp.comment.utils.IdGenerator;
import cn.tt.tuantuanerp.tuantuanerp.comment.web.ServiceCode;
import cn.tt.tuantuanerp.tuantuanerp.product.service.ISkuService;
import cn.tt.tuantuanerp.tuantuanerp.purchase.service.IPurchaseService;
import cn.tt.tuantuanerp.tuantuanerp.purchase.service.ISupplierService;
import cn.tt.tuantuanerp.tuantuanerp.purchase.webapi.mapper.PurchaseMapper;
import cn.tt.tuantuanerp.tuantuanerp.purchase.webapi.mapper.PurchaseProductMapper;
import cn.tt.tuantuanerp.tuantuanerp.purchase.webapi.mapper.SupplierMapper;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zms
 * 采购表的业务逻辑层
 */
@DubboService
@Service
@Slf4j
public class PurchaseServiceImpl implements IPurchaseService {
    @Autowired
    PurchaseMapper mapper;
    @Autowired
    PurchaseProductMapper purchaseProductMapper;

   @DubboReference
   ISkuService serviceSku;

    @Autowired
    SupplierMapper supplierMapper;

    /**
     * @author zms
     * 新增采购单
     **/
    @Override
    public void addPurchase(PurchaseStandardDTO standardDTO, LoginPrincipal loginPrincipal) {
        log.debug ( "前端数据"+standardDTO );
        log.debug ( "loginp:{}",loginPrincipal );
        //判断有没有商品数据
        standardDTO.setPurchaseId ( IdGenerator.getPurchaseId ( loginPrincipal ) );
        List<PurchaseProduct> list = standardDTO.getList ();
        if(list==null){
            throw new ServiceException ( ServiceCode.ERR_NOT_FOUND,"商品的数据为空，请添加商品" );
        }
//        SupplierStandardVO byName = supplierMapper.getByName ( standardDTO.getSupplierName () );
//        if(byName==null){
//            throw  new ServiceException ( ServiceCode.ERR_INSERT,"供应商不存在，请先添加供应商信息" );
//        }
        //添加完信息后的各商品
        List<PurchaseProduct> listNew=new ArrayList<> ();
        //定义变量获取商品总数量
        int num=0;
        //定义商品价格
        BigDecimal total=new BigDecimal ( 0 );
        //计算采购单的数据
        for(PurchaseProduct ppad:list){
            ppad.setPurchaseId ( standardDTO.getPurchaseId () );
            //计算商品数量
            num+=ppad.getAmount ();
            //计算总金额
            total= total.add ( ppad.getPrice ().multiply ( new BigDecimal ( ppad.getAmount () ) ) );
            log.debug ( "total{}",total );
            listNew.add ( ppad );

        }
        log.debug ( "{}",total );
        Purchase purchase=new Purchase ();
        if(mapper.getPurchaseById ( standardDTO.getPurchaseId () )!=null){
            throw  new ServiceException ( ServiceCode.Err_IS_EXIST,"该订单数据已存在,请更改订单id" );
        }
        //设置插入的采购单信息
        BigDecimal amount=total.subtract ( standardDTO.getAmountPaid () );
        BeanUtils.copyProperties ( standardDTO,purchase );
        purchase.setOrderTime ( LocalDateTime.now ());
        purchase.setPartOrder(loginPrincipal.getUsername());
        purchase.setCountProduct ( num );
//        purchase.setSupplierId ( byName.getId () );
        purchase.setPurchasesState ( 0 );
        purchase.setAmountOutstanding (  amount);
        purchase.setTotalMoney ( total );
        log.debug("purchase:{}",purchase);
        log.debug("listNew:{}",listNew);
        mapper.insertPurchase ( purchase );
        purchaseProductMapper.insertBatch (listNew  );

        //定义变量接收采购单号
        String purchaseId=standardDTO.getPurchaseId();

        //查询采购商品表
        List<PurchaseProductListItemVO> listByPurchaseId = purchaseProductMapper.getListByPurchaseId(standardDTO.getPurchaseId());
        //定义数组为转换做准备
        SkuPurchaseInfo[] skuPurchaseInfos={};
        //定义集合储存相关信息
        List<SkuPurchaseInfo> sku=new ArrayList<>();
        for(PurchaseProductListItemVO pp:listByPurchaseId){
            SkuPurchaseInfo skuPurchaseInfo=new SkuPurchaseInfo();
            skuPurchaseInfo.setSkuId(pp.getSkuId());
            skuPurchaseInfo.setTransitNum(pp.getAmount());
            //将对象放入集合
            sku.add(skuPurchaseInfo);
        }
        skuPurchaseInfos=sku.toArray(skuPurchaseInfos);
        log.debug("purchase:{}",purchaseId);
        log.debug("skuPurchase数组：{}",skuPurchaseInfos);
        serviceSku.setPurchaseInfoBat(purchaseId,skuPurchaseInfos,loginPrincipal);
    }


    /**
     * @author 根据id删除采购单
     **/
    @Override
    public void deletePurchase(String id) {
        PurchaseStandardVO purchaseById = mapper.getPurchaseById(id);
        if(purchaseById==null){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"该条信息不存在");
        }
        if(purchaseById.getPurchasesState ()!=0){
            throw new ServiceException(ServiceCode.ERR_DELETE,"该采购单的状态不允许删除");
        }

        int i = mapper.deletePurchase(id);
        if(i!=1){
            throw  new ServiceException(ServiceCode.ERR_DELETE,"删除失败");
        }
        purchaseProductMapper.deleteById(id);
    }


    /**
     * 根据id查询采购详情
     * @param id
     */
    @Override
    public PurchaseDetailVO getById(String id,LoginPrincipal loginPrincipal) {

        PurchaseStandardVO purchaseById = mapper.getPurchaseById ( id );
        if(purchaseById==null){
            throw new ServiceException ( ServiceCode.ERR_NOT_FOUND, "采购单不存在" );
        }
        PurchaseDetailVO purchaseDetailVO=new PurchaseDetailVO ();
        //将采购单部分值传入 PurchaseDetailVO
        BeanUtils.copyProperties ( purchaseById,purchaseDetailVO );
        //定义集合接收商品信息
        List<SkuForPurchaseVO> list=new ArrayList<> ();
        //获取采购商品id
        List<PurchaseProductListItemVO> listByPurchaseId = purchaseProductMapper.getListByPurchaseId ( id );
        for(PurchaseProductListItemVO p:listByPurchaseId){

            SkuForPurchaseVO skuFroPurchase = serviceSku.getSkuFroPurchase ( p.getSkuId (), loginPrincipal );
            //将商品信息加入list集合
            list.add ( skuFroPurchase );

        }
        purchaseDetailVO.setOrderTime ( purchaseById.getOrderTime () );
        purchaseDetailVO.setSku ( list );

        return purchaseDetailVO;
    }


    /**
     * @author zms
     * 采购信息列表
     */

    @Override
    public List<PurchaseStandardListVO> list(Integer currentSize,Integer pageSize) {
        //分页查询
        PageHelper.startPage(currentSize,pageSize);
        List<PurchaseStandardListVO> list = mapper.list();
        return list;
    }


    /**
     * @author zms
     *根据待采购信息
     */
    @Override
    public List<PurchaseStandardListVO> listPrepare(Integer currentPage, Integer pageSiz) {
        PageHelper.startPage ( currentPage,pageSiz );
        List<PurchaseStandardListVO> purchaseStandardListVOS = mapper.listByPurchaseState ( 0 );
        return purchaseStandardListVOS;
    }

    /**
     * 查询采购中信息
     * @return
     */

    @Override
    public List<PurchaseStandardListVO> listPurchasing(Integer currentPage,Integer pageSiz) {
        PageHelper.startPage ( currentPage,pageSiz );
        List<PurchaseStandardListVO> purchaseStandardListVOS = mapper.listByPurchaseState ( 1 );
        return purchaseStandardListVOS;
    }


    /**
     * 查询已完成信息
     * @return
     */

    @Override
    public List<PurchaseStandardListVO> listFinished(Integer currentPage,Integer pageSiz) {
        PageHelper.startPage ( currentPage,pageSiz );
        List<PurchaseStandardListVO> purchaseStandardListVOS = mapper.listByPurchaseState ( 2 );
        return purchaseStandardListVOS;
    }


    /**
     * @param id 采购单id
     *           修改为采购中
     * @author zms
     */

    @Override
    public void updateStateToPurchasing(String id) {
        PurchaseStandardVO purchaseById = mapper.getPurchaseById ( id );
        //当前采购单的状态不为已完成和采购中
        if (purchaseById.getPurchasesState () != 0) {
            throw new ServiceException ( ServiceCode.ERR_BAD_REQUEST, "当前状态不能修改" );
        }
        mapper.updatePurchasesStateToPurchasing ( id );
    }

    /**
     * @param id 采购单id
     *           修改为已完成
     * @author zms
     */

    @Override
    public void updateStateToFinish(String id) {
        PurchaseStandardVO purchaseById = mapper.getPurchaseById ( id );
        //当前采购单的状态不为已完成
        if (purchaseById.getPurchasesState () == 3) {
            throw new ServiceException ( ServiceCode.ERR_BAD_REQUEST, "当前状态不能修改" );
        }
        mapper.updatePurchasesStateToFinish ( id );

    }

    @Override
    public int totalData(Integer index) {
        //判断前段传过来的参数
        if(index==0){
            List<PurchaseStandardListVO> list = mapper.list();
            if(list==null){
                return 0;
            }
            return list.size();
        }else if(index==1){
            List<PurchaseStandardListVO> list = mapper.listByPurchaseState(0);
            if(list==null){
                return 0;
            }
            return list.size();
        }else if(index==2){
            List<PurchaseStandardListVO> list = mapper.listByPurchaseState(1);
            if(list==null){
                return 0;
            }
            return list.size();
        }else {
            List<PurchaseStandardListVO> list = mapper.listByPurchaseState(2);
            if(list==null){
                return 0;
            }
            return list.size();
        }
    }

    /**
     * @author zms
     * @param loginPrincipal
     * 入库
     */
    @Override
    public void stockIn(String purchaseId,LoginPrincipal loginPrincipal) {
        log.debug("xxxxx：{}",loginPrincipal.getUsername());
        PurchaseStandardVO purchaseById1 = mapper.getPurchaseById ( purchaseId );
        //判断当前是否已经经过采购
        if(purchaseById1.getPurchasesState ()==0){
            throw  new ServiceException(ServiceCode.ERR_BAD_REQUEST,"请先采购再入库");
        }
        //判断当前采购单是否已经入库
        if(purchaseById1.getPurchasesState()==2){
            throw  new ServiceException(ServiceCode.ERR_BAD_REQUEST,"当前采购单已经入库");
        }
        //创建需要修改状态的对象role
        Purchase purchase=new Purchase();
        purchase.setPurchaseId(purchaseId);
        purchase.setPurchasesState(2);
        purchase.setLastEntryTime(LocalDateTime.now());
        purchase.setEntryEmployee(loginPrincipal.getUsername());
        mapper.updatePurchase(purchase);
        //更新后将数据查询出来
        PurchaseStandardVO purchaseById = mapper.getPurchaseById(purchaseId);
        log.debug("更新后的数据：{}",purchaseById);
        //获取采购天数
        Duration between = Duration.between(purchaseById.getOrderTime(), purchaseById.getLastEntryTime());
        long purchaseDays=between.toDays()+1;
        log.debug("采购天数：{}",purchaseDays);
        //入库之后将采购时间和上次采购价格更新到sku表
        //获取采购商品信息
        List<PurchaseProductListItemVO> listByPurchaseId = purchaseProductMapper.getListByPurchaseId(purchaseId);
        //定义数组储存传到sku的信息
        SkuPurchaseInfo []sku={};
        //定义集合将循环的对象存入
        List<SkuPurchaseInfo> skuPurchaseInfos=new ArrayList<>();
        for (PurchaseProductListItemVO p: listByPurchaseId) {
            SkuPurchaseInfo skuPurchaseInfo=new SkuPurchaseInfo();
            skuPurchaseInfo.setSkuId(p.getSkuId());
            skuPurchaseInfo.setTransitNum ( -1*p.getAmount (  ) );
            skuPurchaseInfo.setPurchaseDays((int)purchaseDays);
            skuPurchaseInfo.setLastPurchasePrice(p.getPrice());
            //将赋值好的对象放入集合中
            skuPurchaseInfos.add(skuPurchaseInfo);
            //将集合转为数组
            sku=skuPurchaseInfos.toArray(sku);
        }
        log.debug("数组：{}",sku);
        serviceSku.setPurchaseInfoBat(purchaseId,sku,loginPrincipal);

    }

    /**
     * 采购
     * @param purchaseId
     * @param loginPrincipal
     */

    @Override
    public void purchasing(String purchaseId, LoginPrincipal loginPrincipal) {
        log.debug("采购：{}",loginPrincipal.getUsername());
        //判断当前采购单是否已经入库
        PurchaseStandardVO purchaseById = mapper.getPurchaseById ( purchaseId );
        if(purchaseById.getPurchasesState()==2||purchaseById.getPurchasesState ()==1){
            throw  new ServiceException(ServiceCode.ERR_BAD_REQUEST,"当前采购单已经在采购或者已经入库");
        }
        //创建需要修改状态的对象
        Purchase purchase=new Purchase();
        purchase.setPurchaseId(purchaseId);
        purchase.setAmountPaid ( purchaseById.getTotalMoney () );
        purchase.setPurchasesState(1);
        purchase.setAmountOutstanding (new BigDecimal ( 0 ));
        purchase.setPurchasesEmployee (loginPrincipal.getUsername());
        mapper.updatePurchase(purchase);
    }

    /**
     * @author  zms
     * 修改采购信息
     */
    @Override
    public void updatePurchase(String purchaseId,LoginPrincipal loginPrincipal) {
        //判断采购单存不存在
        PurchaseStandardVO purchaseById = mapper.getPurchaseById ( purchaseId );
        if(purchaseById==null){
            throw  new ServiceException ( ServiceCode.ERR_NOT_FOUND,"该采购单不存在" );
        }

    }
}
